<template>
  <div>
    <!-- 搜索条件 -->
    <el-card v-show="showQueryForm" class="form-card">
      <QueryForm ref="queryFormRef" :form-data="queryFormData" :items="queryFormItems" :model="queryFormData" :show-control="true" label-width="82px">
        <QueryFormItem label="创建时间" :col-multiple="1.2">
          <el-date-picker v-model="pickerDate"
                          :shortcuts="pickerShortcuts"
                          class="card-header-extra-action"
                          clearable
                          end-placeholder="结束日期"
                          format="YYYY-MM-DD"
                          start-placeholder="开始日期"
                          type="daterange"
                          value-format="YYYY-MM-DD"/>
        </QueryFormItem>

        <template #control>
          <el-button icon="Search" type="info" @click="handleSearch">{{ $t('form.search') }}</el-button>
          <el-button icon="Refresh" @click="handleResetQueryForm">{{ $t('form.reset') }}</el-button>
        </template>
      </QueryForm>
    </el-card>

    <!-- 统计信息 -->
    <el-row class="panel-group" :gutter="8">
      <el-col :md="6" :sm="12" class="card-panel-col">
        <card-panel :decimals="2"
                    :model-value="statisticsData.payment"
                    icon-class="money"
                    icon-style="style1"
                    panel-text="订单现金总额">
        </card-panel>
      </el-col>

      <el-col :md="6" :sm="12" class="card-panel-col">
        <card-panel :decimals="2"
                    :model-value="statisticsData.subsidy"
                    icon-class="rose"
                    icon-style="style2"
                    panel-text="应返总额">
        </card-panel>
      </el-col>

      <el-col :md="6" :sm="12" class="card-panel-col">
        <card-panel :decimals="2"
                    :model-value="statisticsData.received"
                    icon-class="ribbon"
                    icon-style="style3"
                    panel-text="已返总额">
        </card-panel>
      </el-col>

      <el-col :md="6" :sm="12" class="card-panel-col">
        <card-panel :decimals="2"
                    :model-value="statisticsData.surplus"
                    icon-class="ribbon"
                    icon-style="style4"
                    panel-text="剩余待返">
        </card-panel>
      </el-col>
    </el-row>

    <!-- 列表数据 -->
    <el-card class="content-card">
      <el-tabs v-model="subsidyType" @tab-change="handleChangeSubsidyType">
        <el-tab-pane v-for="item in subsidyTypeOptions" :key="item.value" :label="`${item.label}`" :name="item.value"></el-tab-pane>
      </el-tabs>

      <!-- 工具栏 -->
      <table-toolbar v-model:columns="columns"
                     v-model:show-query-form="showQueryForm"
                     v-model:size="size"
                     v-model:stripe="stripe"
                     @refresh="handleSearch">
      </table-toolbar>

      <!-- 列表记录 -->
      <div class="table-wrapper">
        <!-- 列表数据 -->
        <el-table ref="tableRef"
                  v-loading="loading"
                  :data="tableData"
                  :size="size"
                  :stripe="stripe"
                  row-key="id"
                  show-overflow-tooltip
                  @select="handleSelectChange"
                  @select-all="handleSelectAll"
                  @sort-change="handleSortChange">
          <template #empty>
            <el-empty class="table-empty" description="暂无数据"/>
          </template>

          <table-column :columns="columns">
            <template #type="scope">
              <DictTag v-model="scope.row.type" :circle="false" dict-type="queue_subsidy_type"/>
            </template>

            <template #status="scope">
              <DictTag v-model="scope.row.status" :circle="false" dict-type="queue_subsidy_status" effect="plain"/>
            </template>

            <template #user_id="scope">
              <UserInfoLink :user-id="scope.row.user_id"/>
            </template>

            <template #public_status="scope">
              <DictTag v-model="scope.row.public_status" :circle="false" dict-type="sys_open" effect="plain"/>
            </template>

            <template #public_queue_type="scope">
              <DictTag v-model="scope.row.public_queue_type" :circle="false" dict-type="public_queue_type" effect="plain"/>
            </template>

            <template #operations="scope">
              <!-- 查看 -->
              <el-button v-permission="'subsidy:queue:info'" link type="info" @click="handleShowInfo(scope.row.id)">查看</el-button>
              <!-- 操作 0:补贴中 1:已完成 2:已作废 -->
              <template v-if="hasPermission('subsidy:queue:operations')">
                <el-button v-if="scope.row.status === 0" link type="danger" @click="handleCancel(scope.row)">作废</el-button>
                <el-button v-if="scope.row.status === 2" link type="success" @click="handleRecover(scope.row)">恢复</el-button>
              </template>
            </template>
          </table-column>
        </el-table>

        <!-- 分页操作 -->
        <el-pagination v-if="totalCount > 0"
                       :current-page="pageQuery.pageNum"
                       :page-size="pageQuery.pageSize"
                       :page-sizes="pageSizes"
                       :total="totalCount"
                       background
                       class="table-pagination"
                       layout="total, sizes, prev, pager, next"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </el-card>

    <!-- 弹窗操作 -->
    <QueueSubsidyInfoDrawer ref="infoRef"/>
  </div>
</template>

<script lang="tsx" setup>
import { computed, h, onBeforeMount, reactive, ref } from 'vue';
import { QueryForm, QueryFormItem } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import useTableSelection from '@/hooks/use-table-selection';
import { ElLoading, ElMessageBox, ElNotification, TableInstance, TabsPaneContext } from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import { computedOperateWidth, pickerShortcuts, toDecimal } from '@/utils';
import { QueryFormItemRule } from '@/components/query-form/constants.ts';
import { UserInfoLink } from '@/components/user-info-link';
import { DictTag } from '@/components/dict-tag';
import { subsidyQueueCancel, subsidyQueueList, subsidyQueueRecover } from '@/api/api-subsidy.ts';
import { hasPermission } from '@/utils/permission.ts';
import QueueSubsidyInfoDrawer from './info-drawer.vue';
import { dictTypeMap } from '@/utils/global-dict.ts';
import { CardPanel } from '@/components/other';

defineOptions({name: 'subsidy-queue-list'});

// 查询
const queryFormData = reactive({
  user_id: undefined,
  account: undefined,
  type: undefined,
  status: undefined,
  order_no: undefined,
  store_id: undefined,
  public_status: undefined,
  public_queue_type: undefined,
  public_queue_code: undefined,
  // 时间范围 格式 2023-01-01~2023-01-31
  date: undefined,
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();
const queryFormItems = ref<QueryFormItemRule[]>([
  {type: 'input', prop: 'user_id', label: '用户编号', placeholder: '请输入用户编号', clearable: true},
  {type: 'input', prop: 'account', label: '用户账号', placeholder: '请输入用户账号', clearable: true,},
  {type: 'input', prop: 'order_no', label: '订单号', placeholder: '请输入订单号', clearable: true,},
  {type: 'input', prop: 'store_id', label: '店铺编号', placeholder: '请输入店铺编号', clearable: true,},
  // {type: 'dict-select', prop: 'type', label: '补贴类型', placeholder: '请选择补贴类型', dictType: 'queue_subsidy_type', clearable: true,},
  {type: 'dict-select', prop: 'status', label: '补贴状态', placeholder: '请选择补贴状态', dictType: 'queue_subsidy_status', clearable: true,},
  {type: 'dict-select', prop: 'public_status', label: '公排状态', placeholder: '请选择公排状态', dictType: 'sys_open', clearable: true,},
  {type: 'dict-select', prop: 'public_queue_type', label: '公排类型', placeholder: '请选择公排类型', dictType: 'public_queue_type', clearable: true,},
  {type: 'input', prop: 'public_queue_code', label: '公排编码', placeholder: '请输入公排编码', clearable: true,},
]);

// 列表数据
const tableRef = ref<TableInstance>();
const tableData = ref<any[]>([]);
const totalCount = ref(0);
const pickerDate = ref<any[]>([]);

// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0
  if (hasPermission('subsidy:queue:info')) count += 1
  if (hasPermission('subsidy:queue:operations')) count += 1
  return computedOperateWidth(count);
});

// 列设置
const columns = ref<TableColumnData[]>([
  {prop: 'id', label: '编号', width: 100, align: 'center', sortable: 'custom'},
  {prop: 'rank', label: '店铺排名', width: 100, align: 'center', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'region_rank', label: '公排排名', width: 100, align: 'center', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'type', label: '补贴类型', width: 120, align: 'center', sortable: 'custom'},
  {prop: 'status', label: '补贴状态', width: 120, align: 'center', sortable: 'custom'},
  {prop: 'user_id', label: '用户编号', width: 110, align: 'center', sortable: 'custom'},
  {prop: 'store_id', label: '店铺编号', width: 110, align: 'center', sortable: 'custom'},
  {prop: 'order_no', label: '订单号', minWidth: 180, align: 'right', sortable: 'custom'},
  {prop: 'payment', label: '订单金额', minWidth: 120, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val ? toDecimal(val, 2) : '-'}</span>},
  {prop: 'subsidy', label: '应返金额', minWidth: 120, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val ? toDecimal(val, 4) : '-'}</span>},
  {prop: 'received', label: '已返金额', minWidth: 120, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val ? toDecimal(val, 4) : '-'}</span>},
  {prop: 'rebate_total', label: '商家让利', minWidth: 120, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val ? toDecimal(val, 4) : '-'}</span>},
  {prop: 'consumer_reward', label: '消费者奖励', minWidth: 125, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val ? toDecimal(val, 4) : '-'}</span>},
  {prop: 'first_reward', label: '门店第一奖励', minWidth: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val ? toDecimal(val, 4) : '-'}</span>},
  {prop: 'average_reward', label: '门店加权奖励', minWidth: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val ? toDecimal(val, 4) : '-'}</span>},
  {prop: 'public_first_reward', label: '公排第一奖励', minWidth: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val ? toDecimal(val, 4) : '-'}</span>},
  {prop: 'public_average_reward', label: '公排加权奖励', minWidth: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val ? toDecimal(val, 4) : '-'}</span>},
  {prop: 'public_status', label: '公排状态', minWidth: 120, align: 'center', sortable: 'custom'},
  {prop: 'public_queue_type', label: '公排类型', minWidth: 120, align: 'center', sortable: 'custom'},
  {prop: 'public_queue_code', label: '公排编码', minWidth: 120, align: 'center', sortable: 'custom'},
  {prop: 'payment_time', label: '支付时间', width: 180, align: 'center', sortable: 'custom'},
  {prop: 'create_time', label: '创建时间', width: 180, align: 'center', sortable: 'custom'},
  {prop: 'update_time', label: '更新时间', width: 180, align: 'center', sortable: 'custom'},
]);

onBeforeMount(() => {
  if (operateWidth.value > 0) {
    columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'left', headerAlign: 'center'},)
  }
  // 重置查询表单
  handleResetQueryForm();
});

const [loading, setLoading] = useLoading(false);
const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true, true);
const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState;
const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods;
const {handleSelectChange, handleSelectAll, multipleSelection, clearSelection} = useTableSelection(tableData, tableRef);

/** 统计数据 */
const statisticsData = reactive({
  payment: 0,
  subsidy: 0,
  received: 0,
  surplus: 0
});

// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // 时间范围参数
    // @ts-ignore
    queryFormData.date = pickerDate.value && pickerDate.value.length == 2 ? pickerDate.value[0] + '~' + pickerDate.value[1] : undefined
    queryFormData.type = subsidyType.value
    // 查询数据
    const {data} = await subsidyQueueList({
      page_num: pageQuery.pageNum,
      page_size: pageQuery.pageSize,
      order_mode: pageQuery.orderMode,
      order_column: pageQuery.orderColumn,
      ...queryFormData,
    });
    // 结果转换
    tableData.value = data.list;
    totalCount.value = data.pages.total_count;
    // 统计信息
    statisticsData.payment = data.statistics.payment;
    statisticsData.subsidy = data.statistics.subsidy;
    statisticsData.received = data.statistics.received;
    statisticsData.surplus = data.statistics.surplus;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

// 重置查询条件
const handleResetQueryForm = () => {
  pickerDate.value = [];
  clearSelection();
  handleResetForm();
};

/** 查看详情 */
const infoRef = ref();
const handleShowInfo = (id: number) => {
  infoRef.value?.open(id);
};

/** 补贴类型 */
const subsidyType = ref<any>(10);
const subsidyTypeOptions = computed(() => {
  return dictTypeMap['queue_subsidy_type'] || [];
});

/** Tab 改变时触发 */
const handleChangeSubsidyType = (tab: TabsPaneContext, event: Event) => {
  fetchDataList();
};

/** 作废操作 */
const handleCancel = (row: any) => {
  ElMessageBox.confirm(h('p', null, ['是否将该记录改为 ', h('span', {style: 'font-weight: bold;'}, '已作废'), ` 状态吗 ？`,]), '提示', {
    type: 'warning',
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    subsidyQueueCancel(row.id).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 刷新列表数据
      handleSearch();
    }).finally(() => loading.close())
  }).catch(() => {

  });
};

/** 恢复操作 */
const handleRecover = (row: any) => {
  ElMessageBox.confirm(h('p', null, ['是否将该记录改为 ', h('span', {style: 'font-weight: bold;'}, '补贴中'), ` 状态吗 ？`,]), '提示', {
    type: 'warning',
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    subsidyQueueRecover(row.id).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 刷新列表数据
      handleSearch();
    }).finally(() => loading.close())
  }).catch(() => {

  });
};
</script>

<style lang="scss" scoped>

</style>
